package com.lysj.bhp.approve.service;

import com.lysj.bhp.approve.base.ApproveContent;
import com.lysj.bhp.approve.domain.ApproveRecord;
import com.lysj.bhp.system.domain.VerifyPhone;
import com.lysj.bhp.system.repository.VerifyPhoneRepository;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

@Service
@Transactional
public class PhoneCertificationService extends ApproveContent {

    @Resource
    VerifyPhoneRepository verifyPhoneRepository;

    public Resp phoneCertification(String areacode, String phone, String verify) {
        //查询用户输入的验证码是否正确
        String message = verifyCode(phone, verify);
        if (!ParamUtil.isBlack(message)) {
            return new Resp(Resp.PARAM_ERROR, message);
        }
        //查询用户是否已经进行过一级认证
        ApproveRecord approveRecordQuery = approveRecordRepository.findByUserId(currentUser().getUserId());
        if (null != approveRecordQuery) {
            return new Resp(Resp.PARAM_ERROR, "您已经进行过手机认证,请勿重复认证");
        }
        //去用户表查询手机号是否已经被使用
        int phoneNum = userContent.userRepository.countByAreaCodeAndPhone(areacode, phone);
        if (phoneNum >= 1) {
            return new Resp(Resp.PARAM_ERROR, "该手机号已经被使用");
        }
        //把区号一级手机号码,保存到用户表中
        currentUser().setAreaCode(areacode);
        currentUser().setPhone(phone);
        //创建认证表
        ApproveRecord approveRecord = new ApproveRecord();
        approveRecord.setUserId(currentUser().getUserId());
        approveRecord.setEmail(currentUser().getEmail());
        approveRecord.setInfoStatus(1); //一级认证
        userContent.userRepository.save(currentUser());
        approveRecordRepository.save(approveRecord);
        return new Resp("手机认证成功");
    }

    public String verifyCode(String phone, String verify) {
        String message = "";
        if (ParamUtil.isBlack(verify)) {
            return  message = "验证码不能为空";
        }
        VerifyPhone verifyQuery = verifyPhoneRepository.findOne(phone);
        if (verifyQuery == null) {
            return   message = "验证码错误";
        }
        if (!verify.equalsIgnoreCase(verifyQuery.getVerify())) {
            return   message = "验证码错误";
        }
        if (verifyQuery.getExpires() < System.currentTimeMillis()) {
            return   message = "验证码已失效";
        }
        return message;
    }
}
